package com.example.demo.Client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.controller.ClientController;
import com.example.demo.pojo.Account;
import com.example.demo.pojo.Friend;
import com.example.demo.pojo.Messages;
import com.example.demo.pojo.Msg;
import javafx.scene.control.Label;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Send extends Thread{
    Socket socket;
    ObjectOutputStream out;
    ObjectInputStream in;
    ClientController clientController;

    public void setClientController(ClientController clientController) {
        this.clientController = clientController;
    }

    public Send(Socket socket) throws IOException {
        this.socket = socket;
        this.out = new ObjectOutputStream(this.socket.getOutputStream());
        in = new ObjectInputStream(this.socket.getInputStream());
    }

    @Override
    public void run(){
        try {
            while (true){
                Messages messages;
                JSONObject jsonResult;
                Object obj = in.readObject();
                if(obj instanceof JSONObject){
                    jsonResult = (JSONObject) obj;
                    String result = jsonResult.getString("result");
                    List<Friend> friends = JSON.parseArray(result,Friend.class);
                    int size = clientController.data1.size();
                    if(size > 0){
                        clientController.data1.subList(0,size).clear();
                    }
                    for(Friend friend:friends){
                        clientController.data1.add(new Friend(friend.getUsername(),friend.getPort()));
                    }

                    clientController.getFriendList().setItems(clientController.data1);
                }else{
                    messages=(Messages) obj;

                    clientController.data.add(new Msg(messages.getUsername()+" say to you:"+messages.getMsg()));
                    clientController.getCommit().setItems(clientController.data);
                }




            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void sendMsg(String msg,String username,int port) throws IOException {
        out.writeObject(new Messages(msg,username,port));
    }
    public void sendFlush() throws IOException {
        out.writeObject(new Messages("flush"));
    }
    public static <T> List<T> castList(Object obj, Class<T> clazz)
    {
        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>)
        {
            for (Object o : (List<?>) obj)
            {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }
    public void sendAccount(String username) throws IOException {
        out.writeObject(new Account(username));
    }
}
